{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: 'name.txt'",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-6-0de4a8df9ffa>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[0;31m# 逐行处理到另一个文件中\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"name.txt\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'r'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mfread\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'age.txt'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'w'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mfwrite\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      9\u001b[0m     \u001b[0mline\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mfread\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mreadline\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     10\u001b[0m     \u001b[0;32mwhile\u001b[0m \u001b[0mline\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'name.txt'"
     ],
     "output_type": "error"
    }
   ],
   "source": [
    "# 5.2.8 文件操作和pickle\n",
    "\n",
    "# open()函数的第一个参数是文件名，第二个参数是模式。\n",
    "# 文件的模式一共有四种：读取（r）写入（w）追加（a）和读写（r＋）\n",
    "# 如果希望按照二进制数据读取，则将文件模式和b一起使用(wb, r+b)\n",
    "\n",
    "# 逐行处理到另一个文件中\n",
    "with open(\"name.txt\", 'r') as fread, open('age.txt', 'w') as fwrite:\n",
    "    line = fread.readline()\n",
    "    while line:\n",
    "        name, age = line.rstrip().split(',')\n",
    "        fwrite.write('{},{}'.format(age, nmae))\n",
    "        line = fread.readline()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['hello python', 'hello you', 'hello me']\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# 序列化使用pickle模块\n",
    "import pickle\n",
    "lines = [\n",
    "    \"hello python\",\n",
    "    \"hello you\",\n",
    "    \"hello me\"\n",
    "]\n",
    "\n",
    "# 序列化并保存成文件\n",
    "with open('lines.pkl', 'wb') as f:\n",
    "    pickle.dump(lines, f)\n",
    "\n",
    "# 文件读取并反序列化\n",
    "with open('lines.pkl', 'rb') as f:\n",
    "    lines_back = pickle.load(f)\n",
    "print(lines_back)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5.2.10\n",
    "# 多进程（multiprocessing）\n",
    "# 多个文件并行处理\n",
    "from multiprocessing import Process  # , freeze_support\n",
    "import os\n",
    "\n",
    "def process_data(filelist):\n",
    "    for filepath in filelist:\n",
    "        print('Processing  {} ...'.format(filepath))\n",
    "if __name__ == '__main__':\n",
    "    # 如果在windows下，还要加上freeze_support()函数\n",
    "    # freeze_support()\n",
    "    path = \"/Users/vv/\"\n",
    "    full_list = os.listdir(path)\n",
    "    n_total = len(full_list)\n",
    "    n_process = 32\n",
    "    # 每段子列表的平均长度\n",
    "    length = float(n_total) / float(n_process)\n",
    "    # 计算下标尽可能均匀地划分输入文件列表\n",
    "    indices = [int(round(i * length)) for i in range(n_process + 1)]\n",
    "\n",
    "    # 生成每个进程要处理的子文件列表\n",
    "    sublists = [full_list[indices[i]:indices[i + 1]] for i in range(n_process)]\n",
    "    # 生成进程\n",
    "    processes = [Process(target=process_data, args=(x,)) for x in sublists]\n",
    "\n",
    "    # 并行处理\n",
    "    for p in processes:\n",
    "        p.start()\n",
    "    for p in processes:\n",
    "        p.join()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5.2.11 os 模块\n",
    "# 例如'data' 下有三个子文件夹 'dog' 'cat' 'bat' 要生成一个文件对应标签\n",
    "import os\n",
    "label_map = {\n",
    "    'cat': 0,\n",
    "    'dog': 1,\n",
    "    'bat': 2\n",
    "}\n",
    "\n",
    "with open('data.txt', 'w') as f:\n",
    "    # 遍历所有文件，dirs 是所有子文件夹名，files 是所有文件名\n",
    "    for root, dirs, files in os.walk('data'):\n",
    "        for filename in files:\n",
    "            # 获得文件完整路径\n",
    "            filepath = os.sep.join([root, filename])\n",
    "            # 获得当前文件夹名称\n",
    "            dirname = root.split(os.sep)[-1]\n",
    "            # 得到标签\n",
    "            label = label_map[dirname]\n",
    "            line = '{},{}\\n'.format(filepath, label)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "filepath,label\n\n"
     ]
    }
   ],
   "source": [
    "# 复制、移动、修改文件名\n",
    "# 使用shell 要比使用python方便\n",
    "\n",
    "import os, shutil\n",
    "filepath0 = 'data/bat/IMG_-0.jpg'\n",
    "filepath1 = 'data/bat/IMG_-1.jpg'\n",
    "# 修改文件名\n",
    "os.system('mv {} {}'.format(filepath0,filepath1))\n",
    "# os.rename(filepath0, filepath1)\n",
    "# 创建文件夹\n",
    "dirname = 'data_samples'\n",
    "os.system('mkdir -p {}'.format(dirname))\n",
    "\n",
    "# if not os.path.exists(dirname):\n",
    "#     os.mkdir(dirname)\n",
    "\n",
    "# 拷贝文件\n",
    "os.system('cp {} {}'.format(filepath0, filepath1))\n",
    "shutil.copy(filepath0, filepath1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
